<template>
  <div class="app-container">
    <div id="shang">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="地址检索" prop="hospitalName">
        <el-input
          v-model="queryParams.hospitalName"
          placeholder="输入地址进行区域性搜索知名医院"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    
    <el-table v-loading="loading" :data="hospitalsList" @selection-change="handleSelectionChange" @row-click="go">
      <el-table-column label="医院名称" align="center" prop="hospitalName" />
      <el-table-column label="医院地址" align="center" prop="address" />
      <el-table-column label="医院优势" align="center" prop="hospitalStrengths" />
      <el-table-column label="联系电话" align="center" prop="contactNumber" />
      <el-table-column label="成立年份" align="center" prop="yearOfEstablishment" />
      <el-table-column label="医院规模" align="center" prop="hospitalScale" />
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改传染病知名医院对话框 -->
    <el-dialog :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="医院名称" prop="hospitalName">
          <el-input v-model="form.hospitalName" placeholder="请输入医院名称" />
        </el-form-item>
        <el-form-item label="医院地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入医院地址" />
        </el-form-item>
        <el-form-item label="医院优势" prop="hospitalStrengths">
          <el-input v-model="form.hospitalStrengths" placeholder="请输入医院优势" />
        </el-form-item>
        <el-form-item label="联系电话" prop="contactNumber">
          <el-input v-model="form.contactNumber" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="医院规模" prop="hospitalScale">
          <el-input v-model="form.hospitalScale" placeholder="请输入医院规模" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    </div>

    <!-- 医疗导航地图 -->
    <div id="map"></div>
    <div id="xia">
      <SearcH></SearcH>
      <LocalHistory></LocalHistory>
    </div>
  </div>

</template>

<script>
import SearcH from "@/views/components/SearcH.vue";
import LocalHistory from '@/views/components/LocalHistory.vue';
import AMapLoader from "@amap/amap-jsapi-loader";
import axios from 'axios';
import bus from '@/bus/bus';
import { listHospitals, getHospitals, delHospitals, addHospitals, updateHospitals } from "@/api/hospital/hospitals";

window._AMapSecurityConfig = {
  securityJsCode: "62d3673292931360f7f664e4ef81cc82",
};
export default {
  name: "Hospitals",
  components:{
      SearcH,
      LocalHistory,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 传染病知名医院表格数据
      hospitalsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        hospitalName: null,
        address: null,
        hospitalStrengths: null,
        contactNumber: null,
        yearOfEstablishment: null,
        hospitalScale: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      //地图
      selectedPro: '北京市',
      links: [],
      map: null,
      autoOptions: {
        input: "",
      },
      searchPlaceInput: "",
      hospInput: "",
      begin: "",
      end: "",
      start: [],
      final: [],
      auto: null,
      placeSearch: null,
      district: null,
      polygons: [],
      showHeatOrNot: false,
      heatmap: null,
      heatmapList: null,
      drive: null,
      polyline: null,
      geocoder: null,
      e: null,
      tableData: []
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询传染病知名医院列表 */
    getList() {
      this.loading = true;
      listHospitals(this.queryParams).then(response => {
        this.hospitalsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        hospitalId: null,
        hospitalName: null,
        address: null,
        hospitalStrengths: null,
        contactNumber: null,
        yearOfEstablishment: null,
        hospitalScale: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.hospitalId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加传染病知名医院";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const hospitalId = row.hospitalId || this.ids
      getHospitals(hospitalId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改传染病知名医院";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.hospitalId != null) {
            updateHospitals(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addHospitals(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const hospitalIds = row.hospitalId || this.ids;
      this.$modal.confirm('是否确认删除传染病知名医院编号为"' + hospitalIds + '"的数据项？').then(function() {
        return delHospitals(hospitalIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('hospital/hospitals/export', {
        ...this.queryParams
      }, `hospitals_${new Date().getTime()}.xlsx`)
    },
    //地图相关方法
    initMap() {
      AMapLoader.load({
        key: "be832aaacb575077b410510e9ee0218b", // 申请好的Web端开发者Key，首次调用 load 时必填
        version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: [
          "AMap.ToolBar",
          "AMap.Scale",
          "AMap.HawkEye",
          "AMap.MapType",
          "AMap.Geolocation",
          "AMap.AutoComplete",
          "AMap.PlaceSearch",
          "AMap.Driving",
          "AMap.Geocoder",
        ], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
      })
        .then(AMap => {
          this.map = new AMap.Map("map", {
            //设置地图容器id
            viewMode: "3D", //是否为3D地图模式
            zoom: 10, //初始化地图级别
            center: [121.473667, 31.230525], //初始化地图中心点位置
          });
          this.map.addControl(new AMap.Scale());
          this.map.addControl(new AMap.ToolBar());
          this.map.addControl(new AMap.HawkEye());
          this.map.addControl(new AMap.MapType());
          this.map.addControl(new AMap.Geolocation());
          this.auto = new AMap.AutoComplete(this.autoOptions);

          this.geocoder = new AMap.Geocoder({
            radius: 1000,
            extensions: 'all'
          });
          this.drive = new AMap.Driving({
            policy: 0, //驾车路线规划策略，0是速度优先的策略
            map: this.map,
          });
          //this.drivingSearch = this.drive.search.bind(AMap.Driving);

          this.polyline = new AMap.Polyline({
            strokeColor: '#224456',
            strokeOpacity: 1,
            strokeWeight: 5,
            map: this.map,
          });

          this.placeSearch = new AMap.PlaceSearch({
            map: this.map,
          }); //构造地点查询类
          this.auto.on("select", this.select);
        })
        .catch((e) => {
          this.e = e
          //console.log(e);
        });
    },
    select(e) {
      this.placeSearch.setCity(e.poi.adcode);
      this.placeSearch.search(e.poi.name); //关键字查询查询
      //this.drawBounds(e.poi.name);
      this.map.setZoom(16, true, 1);
    },
    feedBack(msg, feedBackType) {
      this.$message({
        showClose: true,
        message: msg,
        type: feedBackType,
      });
    },
    showHeatMap() {
      this.map.plugin(["AMap.PlaceSearch"], () => {
        //构造地点查询类
        var placeSearch = new AMapLoader.PlaceSearch({
          pageSize: 50, // 单页显示结果条数
          pageIndex: 1, // 页码
          city: this.searchPlaceInput, // 兴趣点城市
          citylimit: true, //是否强制限制在设置的城市内搜索
          //map: this.map, // 展现结果的地图实例
          // panel: 'panel', // 结果列表将在此容器中进行展示。
          // autoFitView: true // 是否自动调整地图视野使绘制的 Marker点都处于视口的可见范围
        });
        //关键字查询
        placeSearch.search("商场", (status, result) => {
          // console.log(result)
          this.getHotChartPos("商场", result);
        });
      });
      this.$notify({
        title: "成功",
        message: "热力图获取成果，但是由于电脑性能，我们仅加载部分数据",
        type: "success",
      });
    },
    getHotChartPos(detail, result) {
      let lengthSize = result.poiList.pageSize;
      const count = result.poiList.count;
      // const lengthPage = count / lengthSize
      if (lengthSize > count) {
        lengthSize = count;
      }
      for (var n = 0; n < lengthSize; n++) {
        // this.map.plugin(['AMap.PlaceSearch'], () => {
        //构造地点查询类
        var realSearch = new AMapLoader.PlaceSearch({
          pageSize: 50, // 单页显示结果条数
          pageIndex: n + 1, // 页码
          city: this.searchPlaceInput, // 兴趣点城市
          citylimit: true, //是否强制限制在设置的城市内搜索
          // map: this.map, // 展现结果的地图实例
          // panel: 'panel', // 结果列表将在此容器中进行展示。
          // autoFitView: true // 是否自动调整地图视野使绘制的 Marker点都处于视口的可见范围
        });
        realSearch.search(detail, (status, result) => {
          // for (var j = 0; j < 50; j++) {
          // this.map.remove(this.map.getAllOverlays('marker'))
          //var centerPoint = [result.poiList.pois[j].location.lng,result.poiList.pois[j].location.lat]
          // console.log(result)
          //热力图
          this.showHatChart(result);
          // }
        });
      }
    },
    showHatChart(result) {
      var info = [];
      for (let i = 0; i < 50; i++) {
        info.push({
          lng: result.poiList.pois[i].location.lng,
          lat: result.poiList.pois[i].location.lat,
          count: 3 * 50 * Math.round(Math.random() * (10 - 2) + 2),
        });
      }
      this.map.plugin(["AMap.HeatMap"], () => {
        //初始化heatmap对象
        this.heatmap = new AMapLoader.HeatMap(this.map, {
          radius: 56, //给定半径
          opacity: [0, 0.5],
          /*,
gradient:{
0.5: 'blue',
0.65: 'rgb(117,211,248)',
0.7: 'rgb(0, 255, 0)',
0.9: '#ffea00',
1.0: 'red'
}
*/
        });
        //设置数据集
        this.heatmap.setDataSet({
          data: info,
          max: 100,
        });
        this.heatmapList.push(this.heatmap);
        this.heatmap.show();
      });
    },
    linePlan(begin, end) {
      // var points = [
      //   { keyword: begin, city: city },
      //   { keyword: end , city: city },
      // ];
      this.geocoder.getLocation([begin, end], (status, result) => {
        if (status === 'complete' && result.info === 'OK') {
          if (result.geocodes.length > 0) {
            var firstGeocode1 = result.geocodes[0];
            var location1 = firstGeocode1.location;
            var firstGeocode2 = result.geocodes[1];
            var location2 = firstGeocode2.location;
            this.start.push(location1.lng, location1.lat);
            this.final.push(location2.lng, location2.lat);
          }
        }
      });

      // this.geocoder.getLocation([end], (status, result) => {  
      //   if (status === 'complete' && result.info === 'OK') {  
      //     if (result.geocodes.length > 0) {  
      //       var firstGeocode = result.geocodes[0];  
      //       var location = firstGeocode.location;  
      //       this.final.push(location.lng, location.lat);
      //     }
      //   }
      // });
    },
    linePlan1() {
      console.log(this.start);
      console.log(this.final);
      var start = this.start;
      var final = this.final;
      console.log(this.polyline.path)
      this.drive.search(start, final, (status, result) => {
        console.log('inner');
        // 绘制路径
        const path = result.routes[0].path;
        console.log(path);
        this.polyline.setPath(path);

      });
      console.log(this.polyline.path)
    },
    go(r, c, e) {
      console.log(c + e)
      this.hospInput = r.hospitalName
    }
  },
  mounted() {
    //DOM初始化完成进行地图初始化
    this.initMap();
  },
  watch: {
    searchPlaceInput(newValue) {
      if (newValue != null) {
        console.log(newValue);
        this.placeSearch.search(newValue);
        //this.drawBounds(newValue);
        this.map.setZoom(16, true, 1);
        // this.linePlan(this.begin,this.end);
        // this.linePlan1();
      }
    },
    hospInput(newValue) {
      if (newValue != null) {
        console.log(newValue);
        this.placeSearch.search(newValue);
        //this.drawBounds(newValue);
        this.map.setZoom(16, true, 1);
        // this.linePlan(this.begin,this.end);
        // this.linePlan1();
      }
    },
    showHeatOrNot(newValue) {
      if (newValue) {
        this.showHeatMap();
      } else {
        this.heatmap.hide();
      }
    },
    selectedPro(newValue) {
      console.log(newValue)
      this.news()
      this.loadaddress()
    }
  },
};
</script>
<style scoped>
#map_warp{
    z-index: 10;
    margin-left: auto;
    margin-right: auto;
    height: 60%;
    width: 100%;
}
#shang {
  height: auto;
  margin-bottom: 20px;
}
#map {
  width: 100%;
  height: 600px;
  margin: 0;
}
#xia {
  width: 100%;
  height: auto;
  margin: 0;
}
</style>